/**
 * 
 */
package com.shop.cloud.Scheduled;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;

import com.shop.cloud.JPush.MsgPushUtils;
import com.shop.cloud.dao.hongfu.UserDao;
import com.shop.cloud.domain.hongfu.Banner;
import com.shop.cloud.domain.hongfu.Message;
import com.shop.cloud.domain.hongfu.RebateBill;
import com.shop.cloud.domain.hongfu.RebateHistory;
import com.shop.cloud.domain.hongfu.User;
import com.shop.cloud.domain.hongfu.UserMember;
import com.shop.cloud.domain.hongfu.UserVip;
import com.shop.cloud.domain.hongfu.VipHistory;
import com.shop.cloud.service.hongfu.IMessageService;
import com.shop.cloud.service.hongfu.IRebateBillService;
import com.shop.cloud.service.hongfu.IRebateHistoryService;
import com.shop.cloud.service.hongfu.UserMemberService;
import com.shop.cloud.service.hongfu.UserVipService;
import com.shop.cloud.service.hongfu.VipHistoryService;
import com.shop.cloud.service.hongfu.impl.BannerService;
import com.shop.cloud.service.hongfu.impl.UserService;

/**
 * @author 作者姓名 E-mail: email地址
 * @version 创建时间：2018年1月10日 上午10:27:34
 * 类说明
 */
/**
 * @author Administrator
 *
 */
@Component
public class ScheduledController {
	
	Logger logger = Logger.getLogger(ScheduledController.class);  

	@Autowired
	private IMessageService messageService;

	@Autowired
	private UserService userService;
	
	@Autowired
	private BannerService bannerService;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private IRebateBillService rebateBillService;
	
	@Autowired
	private IRebateHistoryService rebateHistoryService;
	
	@Autowired
	private UserMemberService userMemberService;
	
	@Autowired
	private UserVipService userVipService;
	
	@Autowired
	private VipHistoryService vipHistoryService;

	//十分钟
	@Scheduled(fixedRate = 600000)
	public void testTasks() {
		//消息定时推送
		System.out.println("开始定时任务：推送消息");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("type", 1);
		params.put("isPush", 0);
		List<Message> messList = messageService.find(params);
		for (Message message : messList) {
			long current = System.currentTimeMillis();
			 //十一分钟
		    long current2 = current + 660000;
			if (message.getDisplayTime()!=null&&current<message.getDisplayTime().getTime() && message.getDisplayTime().getTime()<current2 ) {

				// 极光推送消息:全部
				if (message.getPushType() == 0) {
					MsgPushUtils.buildPushObject_all_all_alert(message.getContent());
					message.setIsPush(1);
					messageService.update(message);
				}
				// 极光推送：门店
				if (message.getPushType() == 1) {
					
					try {
						User user = new User();
						user.setRoleId(message.getPushId());
						List<User> uList = userService.find(user);
						for (User user2 : uList) {
							MsgPushUtils.addJPush(message.getContent(), user2.getId().toString());
							message.setIsPush(1);
							messageService.update(message);
						}
					} catch (APIConnectionException e) {
						e.printStackTrace();
					} catch (APIRequestException e) {
						e.printStackTrace();
					}

				}
			}
		}
		
		//banner图片定时下架
		System.out.println("开始定时任务：banner图片定时下架");
		Banner banner = new Banner();
		banner.setIsDisplay(0);
		List<Banner> bannerlist =bannerService.find(banner);
		for (Banner banner2 : bannerlist) {
			long current = System.currentTimeMillis();
		    if (current > banner2.getSoldoutTime().getTime()) {
		    	//修改上架状态 1-下架
		    	banner.setIsDisplay(1);
		    	bannerService.update(banner);
		    }
		}
		
	}
	
	@Scheduled(cron = "0 0 0 1 * ?")
	public void rebateTasks(){
		
		logger.info("------------每月1号0点执行生成账单开始---------------");
		
		//获取当前所有可返利金额大于1825的用户信息
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("thisLimit", 1825f);
		
		List<User> users = userDao.rebateUsers(params);
		if(null != users && users.size() > 0){
			for(User insUser : users){
				//获取上个月剩余消费金额
				float remainAmount = insUser.getRemainConsumeAmount();
				//倍数
				int num = (int)(remainAmount / 1825f);
				//剩余
				float thisMore = remainAmount % 1825f;
				
				//获取当前的待返利的余额
				float waitAmount = insUser.getWaitRebateBalance();
				waitAmount = waitAmount + (1825f * num);
				//保存当前的待返利余额
				insUser.setWaitRebateBalance(waitAmount);
				//保存当前的剩余消费金额
				insUser.setRemainConsumeAmount(thisMore);
				
				//获取已返利的余额
				float alreadyAmount = insUser.getAlreadyRebateBalance();
				//保存当前可返利余额
				insUser.setCanRebateBalance(alreadyAmount + waitAmount);
				
				//保存定时操作
				userService.update(insUser);
				
				//账单信息
				RebateBill rebateBill = new RebateBill(); 
				rebateBill.setUserId(insUser.getId());
				rebateBill.setAmount(new Float(num));
				Calendar calendar = Calendar.getInstance();
				int year = calendar.get(Calendar.YEAR);
				int month = calendar.get(Calendar.MONTH) + 1;
				rebateBill.setYear(year);
				if(month == 1){
					rebateBill.setMonth(12);
				}else{
					rebateBill.setMonth(month - 1);
				}
				rebateBill.setRemark(year+"/"+month+"/01~"+(year+5)+"/"+month+"/01");
				rebateBill.setCreateTime(new Timestamp((new Date()).getTime()));
				rebateBill.setRemainAmount(1825f * num);
				//保存账单信息
				rebateBillService.insert(rebateBill);
			}
		}
		logger.info("------------每月一号执行生成账单结束---------------");
	}
	
	@Scheduled(cron = "0 0 1 * * ?")
	public void handleRebateTasks(){
		
		logger.info("------------每天1点执行生成返利开始---------------");
		
		//获取可以返利的用户信息列表
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("thisLimit", 0f);
		
		List<User> users = userDao.handleRebateUsers(params);
		if(null != users && users.size() > 0){
			for(User insUser : users){
				//获取用户ID
				Long thisId = insUser.getId();
				//获取该用户账单信息
				RebateBill rebateBill = new RebateBill();
				rebateBill.setUserId(thisId);
				rebateBill.setOrderBy("REBATE_BILL.create_time ASC");
				rebateBill.setStatus(0);
				List<RebateBill> thisList = rebateBillService.find(rebateBill);
				
				//当月返利总额
				float totalAmount = 0f;
				if(null != thisList && thisList.size() > 0){
					for(RebateBill insBill : thisList){
						//循环处理每月账单返利
						float amount = insBill.getAmount();
						totalAmount = totalAmount + amount;
						
						//获取当前账单的剩余返利
						float remainAmount = insBill.getRemainAmount();
						remainAmount = remainAmount - amount;
						insBill.setRemainAmount(remainAmount);
						if(remainAmount <= 0){
							insBill.setStatus(1);
						}
						
						//处理返利历史
						RebateHistory rebateHistory = new RebateHistory(); 
						rebateHistory.setUserId(thisId);
						rebateHistory.setAmount(amount);
						rebateHistory.setType(insBill.getRemark());
						rebateHistory.setMonth(insBill.getMonth());
						Calendar calendar = Calendar.getInstance();
						int year = calendar.get(Calendar.YEAR);
						int month = calendar.get(Calendar.MONTH) + 1;
						rebateHistory.setThisYear(year);
						rebateHistory.setThisMonth(month);
						rebateHistory.setCategory(1); //返利类别:1商品，2会员卡
						rebateHistory.setCreateTime(new Timestamp((new Date()).getTime()));
						//保存返利记录
						rebateHistoryService.insert(rebateHistory);
						
						//保存账单变更
						rebateBillService.update(insBill);
					}
				}
				//获取用户待返利金额
				float waitAmount = insUser.getWaitRebateBalance();
				//获取用户已返利金额
				float alreadyAmount = insUser.getAlreadyRebateBalance();
				//获取当前用户可提现金额
				float canAmount = insUser.getCanWithdrawBalance();
				
				waitAmount = waitAmount - totalAmount;
				insUser.setWaitRebateBalance(waitAmount);
				
				alreadyAmount = alreadyAmount + totalAmount;
				insUser.setAlreadyRebateBalance(alreadyAmount);
				
				canAmount = canAmount + totalAmount;
				insUser.setCanWithdrawBalance(canAmount);
				
				//保存用户定时操作
				userService.update(insUser);
			}
		}
		
		logger.info("------------每天1点执行生成返利结束---------------");
	}
	
	
	@Scheduled(cron = "0 0 9 1 * ?")
//	@Scheduled(cron="*/5 * * * * ?")
	public void rebateVipTasks(){
		logger.info("------------每月1号9点执行生成会员卡返利账单开始---------------");
		 
		List<UserVip> vipList=userVipService.find(new UserVip());
		
		 List<UserMember> userMemberList=userMemberService.find(new UserMember());
		 for (int i = 0; i < userMemberList.size(); i++) {
			 
			UserMember userMember = userMemberList.get(i);
			
			//判断是否过了一个月
			long current =  System.currentTimeMillis();
			long current2 = userMember.getCreateTime().getTime();
			long oneMonth=2592000000L;
//			long oneMonth=150000L;
			if (current-current2>=oneMonth) {
				
				//判断用户是否返回了全部
				if (Integer.parseInt(userMember.getReturnPeriods().split("/")[0])<=Integer.parseInt(userMember.getReturnPeriods().split("/")[1])) {
					for (int j = 0; j < vipList.size(); j++) {
						UserVip userVip = vipList.get(j);
						if (userVip.getLevel().equals(userMember.getLevel())) {
							
							UserVip vip=new UserVip();
							vip.setLevel(userMember.getLevel().toString());
							List<UserVip> list=userVipService.find(vip);
							if (list.size()>0) {
								
								//修改返回的期数
								if (Integer.parseInt(userMember.getReturnPeriods().split("/")[0])!=Integer.parseInt(userMember.getReturnPeriods().split("/")[1])) {
									userMember.setReturnPeriods(Integer.parseInt(userMember.getReturnPeriods().split("/")[0])+1+"/"+Integer.parseInt(userMember.getReturnPeriods().split("/")[1])+"");
									userMemberService.update(userMember);
									
									//赠送金额
									User user=new User();
									user.setId(userMember.getUserId());
									Map<String, Object> params =  new HashMap<String, Object>();
									params.put("key", userMember.getUserId());
									user = userService.findByIdOrPhone(params);
									user.setCanWithdrawBalance(user.getCanWithdrawBalance()+list.get(0).getMonthly());
									user.setVipRebate(user.getVipRebate()+list.get(0).getMonthly().intValue());
									userService.update(user);
									
									//处理返利历史
									Date date=new Date();
									Calendar cale = Calendar.getInstance();
									Calendar cale2 = Calendar.getInstance();
									cale.setTime(date);
									cale.add(Calendar.MONTH, -1);
									Timestamp tim=new Timestamp(cale.getTimeInMillis());
									Timestamp tim2=new Timestamp(cale2.getTimeInMillis());
									RebateHistory rebateHistory = new RebateHistory(); 
									rebateHistory.setUserId(userMember.getUserId());
									rebateHistory.setAmount(list.get(0).getMonthly());
									rebateHistory.setType(tim.toString().split(" ")[0]+"~"+tim2.toString().split(" ")[0]);
									rebateHistory.setMonth(cale.MONTH);
									rebateHistory.setThisYear(cale.get(Calendar.YEAR));
									rebateHistory.setThisMonth(cale2.MONTH+1);
									rebateHistory.setCategory(2); //返利类别:1商品，2会员卡
									rebateHistory.setCreateTime(new Timestamp((new Date()).getTime()));
									//保存返利记录
									rebateHistoryService.insert(rebateHistory);
									
									//保存返利记录
									VipHistory vipHistory=new VipHistory();
									vipHistory.setCreateTime(new Timestamp((new Date()).getTime()));
									vipHistory.setAmount(list.get(0).getMonthly().intValue());
									vipHistory.setUserId(userMember.getUserId());
									vipHistory.setReturnPeriods(userMember.getReturnPeriods());
									vipHistoryService.insert(vipHistory);
								}
							}
						}
					}
			
				}
			}
			
			
			
			
		
		}
		 
		logger.info("------------每月一号9点执行生成账单结束---------------");
	}

	public static void main(String[] args) {
		Timestamp t = new Timestamp(new Date().getTime());
		long t2=System.currentTimeMillis();
		  System.out.println("当前时间："+t.getTime());
		  System.out.println("当前时间："+t2);
	}

}
